package com.xcity.db.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import com.alibaba.fastjson.JSON;
import com.xcity.db.entity.Build;
import com.xcity.game.build.BuildManager;

import naga.x.util.StringUtils;

@Deprecated
public class BuildsTypeHandler extends BaseTypeHandler<BuildManager> {
	
//	static {
//		ParserConfig.getGlobalInstance().putDeserializer(Build.class, new BuildDeserializer(ParserConfig.getGlobalInstance(), Build.class));
//	}
//	
//	static class BuildDeserializer extends JavaBeanDeserializer {
//
//		public BuildDeserializer(ParserConfig config, Class<?> clazz) {
//			super(config, clazz);
//		}
//		
//		public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
//			Build b = new Build();
//			b.setManager(LOCAL.get());
//			return super.deserialze(parser, type, fieldName, b, 0);
//		}
//		
//	}
//	
//	static final ThreadLocal<BuildManager> LOCAL = new ThreadLocal<BuildManager>();

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, BuildManager parameter, JdbcType jdbcType)
			throws SQLException {
		ps.setString(i, parameter != null ? parameter.toString() : null);
	}

	@Override
	public BuildManager getNullableResult(ResultSet rs, String columnName) throws SQLException {
		return parse(rs.getString(columnName));
	}

	@Override
	public BuildManager getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		return parse(rs.getString(columnIndex));
	}

	@Override
	public BuildManager getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		return parse(cs.getString(columnIndex));
	}
	
	private static BuildManager parse(String json) {
		if (StringUtils.isEmpty(json)) {
			return new BuildManager(null, null);
		}
//		BuildManager bm = new BuildManager(null, Collections.emptyList());
//		LOCAL.set(bm);
//		bm.setBuildings(JSON.parseArray(json, Build.class));
//		LOCAL.remove();
//		return bm;
		return new BuildManager(null, JSON.parseArray(json, Build.class));
	}

}
